<?php

/**
 * Client.
 *
 * @author  yyc
 * @version 1.0
 * @package main
 * @date 2017-06-07 0007
 * @time 15:23:30
 */

/**
 *
 * ━━━━━━神兽出没━━━━━━
 * 　　　┏┓　　　┏┓
 * 　　┏┛┻━━━┛┻┓
 * 　　┃　　　　　　　┃
 * 　　┃　　　━　　　┃
 * 　　┃　┳┛　┗┳　┃
 * 　　┃　　　　　　　┃
 * 　　┃　　　┻　　　┃
 * 　　┃　　　　　　　┃
 * 　　┗━┓　　　┏━┛Code is far away from bug with the animal protecting
 * 　　　　┃　　　┃    神兽保佑,代码无bug
 * 　　　　┃　　　┃
 * 　　　　┃　　　┗━━━┓
 * 　　　　┃　　　　　　　┣┓
 * 　　　　┃　　　　　　　┏┛
 * 　　　　┗┓┓┏━┳┓┏┛
 * 　　　　　┃┫┫　┃┫┫
 * 　　　　　┗┻┛　┗┻┛
 *
 * ━━━━━━感觉萌萌哒━━━━━━
 */

namespace server;

use Noodlehaus\Config;
//use Monolog\Handler\GelfHandler;
use Monolog\Handler\RotatingFileHandler;
use Monolog\Logger;
use cmpp\CmppResp;
use cmpp\CmppSend;
class Client
{
    public $config;
    public $log;
    public $client;
    public $cmppConfig;
    public $table;
    private static $instance;
    public function __construct()
    {

        $this->config = new Config(__DIR__ . '/../Config');
        self::$instance =& $this;
        $this->setLog();
        $this->setTable();
        R();
    }

    public static function &get_instance()
    {
        return self::$instance;
    }

    public function setLog()
    {
        $this->log = new Logger($this->config->get('log.log_name', 'SMSGateWay'));
        $this->log->pushHandler(new RotatingFileHandler(__DIR__ . $this->config['log']['log_path'] . 'SMSGateWay.log', $this->config['log']['log_max_files'],$this->config['log']['log_level']));
    }

    public function setTable(){
        $this->table = new \server\Table();
        $this->table->create();
    }

    public function run(){
        $this->cmppConfig = new \cmpp\CmppConfig($this->config);
        $this->client = new \swoole_client(SWOOLE_SOCK_TCP, SWOOLE_SOCK_ASYNC);
        $this->client->on("connect", [$this,"onConnect"]);
        $this->client->on("receive", [$this,"onReceive"]);
        $this->client->on("error", [$this,"onError"]);
        $this->client->on("close", [$this,"onClose"]);
        $this->client->connect($this->cmppConfig->getIP(), $this->cmppConfig->getPort());
    }

    public function onConnect(\swoole_client $cli){
        $msg = CmppSend::connect($this->cmppConfig->getSpid(),$this->cmppConfig->getPassword(),$this->cmppConfig->getVersion());
        $cli->send($msg);
    }

    public function onReceive(\swoole_client $cli,$data){
        $len = strlen($data);
        if($len > 0){
            CmppResp::run($data,$this->client);
        }
    }

    public function onError(\swoole_client $cli){
        L()->error('Connection error '.socket_strerror($cli->errCode));
        //$proc = new Process();
       //$proc->stopB();
    }

    public function onClose(\swoole_client $cli){
        L()->error('Connection close');
        //$proc = new Process();
        //$proc->stopB();
    }


}